﻿using System;
using System.Text;

namespace LeanEngine.Data.Linq.Builder
{
    internal struct CounterQueryBuilder : IQueryBuilder
    {
        #region IQueryBuilder Members

        public string BuildTSQL(LinqQuery linqQuery)
        {
            var selectStatements = linqQuery.Select.GetStatement().Split(' ');

            var commandBuilder = new StringBuilder();

            commandBuilder.Append("SELECT COUNT(");
            commandBuilder.Append(selectStatements[1].Replace(",", string.Empty));
            commandBuilder.Append(") ");
            commandBuilder.Append(Environment.NewLine);
            commandBuilder.Append(linqQuery.From.GetStatement());
            commandBuilder.Append(Environment.NewLine);
            if (linqQuery.JoinList != null)
            {
                foreach (var join in linqQuery.JoinList)
                {
                    commandBuilder.Append(join.GetStatement());
                    commandBuilder.Append(Environment.NewLine);
                }
            }
            if (linqQuery.Where != null)
            {
                commandBuilder.Append(linqQuery.Where.GetStatement());
                commandBuilder.Append(Environment.NewLine);
            }
            if (linqQuery.GroupBy != null)
            {
                commandBuilder.Append(linqQuery.GroupBy.GetStatement());
                commandBuilder.Append(Environment.NewLine);
            }

            return commandBuilder.ToString();
        }

        #endregion
    }
}